package com.discordia.asap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;

//import com.discordia.asap.R.color;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AsapImage extends Activity {
	
	private String imgid = "";
	private Bitmap imgBit = null;
	private String last_msg_id = "-1";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		imgid = bundle.getString("imgid");
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.image);

		try {
			imgBit = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() + "/Android/data/com.discordia.asap/images/" + imgid +".jpg");
			ImageView imageView = (ImageView) findViewById(R.id.imagePortrait);
			imageView.setImageBitmap(imgBit);
			findViewById(R.id.scrollView1).requestFocus();
			getMessages(imageView);
			
			
			// hide the input form
			/*EditText ed = (EditText)findViewById(R.id.img_msg_input);
			InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
			ed.clearFocus();
			//msg_lay.setVisibility(View.GONE);*/
			
		} catch (Exception e) {
			Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
		}
	}
	
	/** Called when the activity is hidden. */
	@Override
	public void onStop() {
		super.onStop();
		imgBit.recycle();
	}

	
	/**
	 * Called when a message upload is requested.
	 * 
	 * @param view
	 *            reference to the widget that was clicked.
	 */
	public void sendMessage(View view) {
		
		try {
			String link = "http://" + AsapActivity.server + AsapActivity.script_folder + "/handle_message.php";
			DefaultHttpClient hc = new DefaultHttpClient();
			HttpPost postMethod = new HttpPost(link);
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			String msg = "";
			
			EditText ed = (EditText)findViewById(R.id.img_msg_input);
			LinearLayout msg_lay = (LinearLayout)findViewById(R.id.msg_lay);
			
			// get the comment from input form and send it
			msg = ed.getText().toString();
			
			if(msg.isEmpty())
				//Toast.makeText(this, "Failed to send", Toast.LENGTH_SHORT).show();
				throw new IOException("Empty comment: please write something!");
				
			nameValuePairs.add(new BasicNameValuePair("id", imgid));
			nameValuePairs.add(new BasicNameValuePair("message", msg));
			
			postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			BasicHttpResponse httpResponse;
			httpResponse = (BasicHttpResponse) hc.execute(postMethod);
			HttpEntity responseEntity = httpResponse.getEntity();

		   /*
		    * From the php script we receive back a stream of data that has to
		    * be parsed.The string with the information we need starts with the
		    * key FEEDBACK_START and continues with all the feedback data. Every
		    * information starts with its feedback key and it is separated from
		    * other informations by a couple of ""
		    * TODO: define a better feedback solution to avoid the use of String.substring()
		    */
			
			InputStream responseStream = responseEntity.getContent();
			
			BufferedReader r = new BufferedReader(new InputStreamReader(responseStream));
			
			String line;
			while ((line = r.readLine()) != null) {
				Log.e("Asap", "Message: " + line);
				if (line.contains("FEEDBACK_START")) {
					String feedback[] = line.split("\"\"");
					for (int k = 0; k < feedback.length; k++) {
						if (feedback[k].contains("FEEDBACK_KEY_MESSAGE")){
							String fdbmessage = feedback[k].substring(20).replace("\"", "");
							//toast to show the feedback message from the script
							Toast.makeText(this, fdbmessage, Toast.LENGTH_SHORT).show();
						}else if (feedback[k].contains("FEEDBACK_KEY_UPLOAD")){
							String fdbmessage = feedback[k].substring(19).replace("\"", "");
							//toast to show the feedback message from the script
							Toast.makeText(this, fdbmessage, Toast.LENGTH_SHORT).show();
						}else if (feedback[k].contains("FEEDBACK_KEY_ID")){//unused
							//String msgid = feedback[k].substring(15).replace("\"", "");
							//msgid: id of the last message sent
						}
					}
				}
			}
				
			r.close();
			
			// hide the input form
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
			ed.clearFocus();
			ed.setText("");
			msg_lay.setVisibility(View.GONE);
			
			//update messages
			getMessages(view);
		}
		catch (IOException ioex) {
			Toast.makeText(this, ioex.getMessage(), Toast.LENGTH_SHORT).show();
			Log.e("Asap", "error: " + ioex.getMessage(), ioex);
		}
	}
	
	/**
	 * Called when a message download is requested.
	 * 
	 * @param view
	 *            reference to the widget that was clicked.
	 */
	public void getMessages(View view) {
		
		try {
			String link = "http://" + AsapActivity.server + AsapActivity.script_folder + "/get_messages.php";
			DefaultHttpClient hc = new DefaultHttpClient();
			HttpPost postMethod = new HttpPost(link);
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("id", imgid));
			nameValuePairs.add(new BasicNameValuePair("message", last_msg_id));
			
			postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			BasicHttpResponse httpResponse;
			
			httpResponse = (BasicHttpResponse) hc.execute(postMethod);
			
			HttpEntity responseEntity = httpResponse.getEntity();
		   /*
		    * From the php script we receive back a stream of data that has to
		    * be parsed.The string with the information we need starts with the
		    * key FEEDBACK_START and continues with all the feedback data. Every
		    * information starts with its feedback key and it is separated from
		    * other informations by a couple of ""
		    * TODO: define a better feedback solution to avoid the use of String.substring()
		    */
			
			InputStream responseStream = responseEntity.getContent();
			
			BufferedReader r = new BufferedReader(new InputStreamReader(responseStream));
			
			String line;
			LinearLayout comments = (LinearLayout) this.findViewById(R.id.commentsLayout);
			//clear the content of the container before adding the messages
			//comments.removeAllViews();
			
			while ((line = r.readLine()) != null) {
				Log.e("Asap", "Message: " + line);
				if (line.contains("FEEDBACK_START")) {
					String feedback[] = line.split("\"\"");
					for (int k = 0; k < feedback.length; k++) {
						if (feedback[k].contains("FEEDBACK_MSG_TEXT")) {
							TextView comment = new TextView(this);
							comment.setText(feedback[k].substring(17).replace("\"", ""));
							//different comments have different different background
							if(k % 2 == 0)
								comment.setBackgroundColor(Color.DKGRAY);
							
							comments.addView(comment);
							//TODO focus to most recent message
						}
					}
				}
			}
			//this.setContentView(sv);
			last_msg_id = Integer.toString(comments.getChildCount());
			r.close();	
		}
		catch (IOException ioex) {
			Log.e("Asap", "error: " + ioex.getMessage(), ioex);
		}		 
	}
	
	
	public void showKeyboard(View view) {
		//final EditText ed = (EditText)findViewById(R.id.img_msg_input);
		LinearLayout ll = (LinearLayout)findViewById(R.id.msg_lay);
		ll.setVisibility(View.VISIBLE);
		//InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
		//imm.showSoftInputFromInputMethod(ed.getWindowToken(), 0);
		//ed.requestFocus();
	}
}
